<?php
declare (strict_types = 1);
namespace app\view\model;
use app\common\model\BaseModel;
use app\user\model\User;

Class ViewText extends BaseModel
{
    // 缓存键值
    public $sr_key = 'ViewText_list';
    public $field = 'uname,text';

    // 获取数据
    public function getList()
    {
        $this->setSrConfig([
            'field' => $this->field,
            'where' => ['show' => 1]
        ]);
        //$list = $this->where('show',1)->order('sort desc')->field('uname,text')->select()->toArray();
        $list = $this->getListCache(false);
        $allData = [];
        $k = 0;
        foreach($list as $item){
            $s = explode(',',$item['uname']);
            if($s && is_array($s)){
                foreach($s as $i){
                    $allData[] = [
                        'sort' => $k,
                        'text' => $item['text'],
                        'username' => $i
                    ];
                    $k++;
                }
            }
            $k++;
        }
        shuffle($allData);
        return $allData;
    }

    // 获取数据
    public function getListB()
    {
        $model = new User();
        $list = [];
        // 获取20个用户名（虚拟用户）
        if($model->where(['is_fictitious'=>1])->count()>0)
            $list = $model->field('nickname')->where(['is_fictitious'=>1])->order('add_time desc ')->limit(0,3)->select()->toArray();
        if(!empty($list)) $list = array_column($list,'nickname');
        if(count($list) < 10){
            $num = 10 - count($list);
            $text_list = $this->getListCache(false);
            $list_1 = $list_2 = [];
            if(!empty($text_list)&&isset($text_list[0]))
                $list_1 = explode(',',$text_list[0]['uname']);
            if(!empty($list_1)&&count($list_1) < $num){
                $number = $num - count($list_1);
                for($i=1;$i<=$number;$i++){
                    $list_2[] = $list_1[rand(0, (count($list_1)-1))];
                }
                $list_2 = array_merge($list_1,$list_2);
            }elseif(count($list_1) > $num) $list_2 = array_rand($list_1,$num);
            else $list_2 = $list_1;
            $list = array_merge($list,$list_2);
        }
        $txt = [
            '恭喜 %s** 邀请好友获得%s喵呗奖励',
            '%s** 通过分享商品获得%s喵呗奖励',
        ];
        $miao = [2,30];
        $miaos = 200;
        sprintf($txt[0], 1, 2, 3);
        $data = [];
        foreach($list as $v){
            $t = rand(0,1);
            if($t == 1) $k = $miao[0] + mt_rand() / mt_getrandmax() * ($miao[1] - $miao[0]);
            else $k = $miaos;
            $data[] = sprintf($txt[$t], mb_substr ( strval($v), 0, 1 ), number_format($k,2,'.',''));
        }
        shuffle($data);
        return $data;
    }


}